<template>



  <div class="container">
    <!-- 第一部分: 头部 -->
    <div class="h-6" />
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        background-color="#545c64"
        text-color="#fff"
        active-text-color="#ffd04b"
        @select="handleSelect"
    >
      <el-menu-item index="1">Pod管理</el-menu-item>
      <el-menu-item index="2">日志</el-menu-item>
<!--      <el-menu-item index="3">详情</el-menu-item>-->
      <el-menu-item index="3">YAML</el-menu-item>
    </el-menu>
    <div class="header shadow" v-if="activeIndex ==='1'">
      <div class="left-group">
        <el-button type="text" @click="goBack">
          <el-icon style="font-size: 20px"><ArrowLeft /></el-icon>
        </el-button>
        <el-input placeholder="请输入内容" v-model="searchText" class="search-input" @input="handleInput">
          <template #append>
            <el-button type="primary" @click="search()">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <!-- 移动的刷新按钮，保留在右侧 -->
      <div class="right-group">
        <el-button @click="refresh">
          <el-icon><Refresh /></el-icon>
          <span> 刷新 </span>
        </el-button>
      </div>
    </div>
    <div class="header shadow" v-if="activeIndex ==='3'">
      <div class="left-group">
        <el-button type="text" @click="goBack">
          <el-icon style="font-size: 20px"><ArrowLeft /></el-icon>
        </el-button>
      </div>

    </div>
    <div class="header shadow" v-if="activeIndex ==='2'">
      <div class="left-group">
        <el-button type="text" @click="goBack">
          <el-icon style="font-size: 20px"><ArrowLeft /></el-icon>
        </el-button>
        <!-- 选择器容器 -->
        <div class="selectors">
          <!-- 第一个选择器 -->
          <el-select v-model="selectedValue1" placeholder="请选择" class="selector"  @change="handlePodChange">
            <el-option
                v-for="option in tableData"
                :key="option.podName"
                :label="option.podName"
                :value="option.podName"
            >
            </el-option>
          </el-select>
          <!-- 第二个选择器 -->
          <el-select v-model="selectedValue2" placeholder="请选择" class="selector" @change="handleContainers">
            <el-option
                v-for="name in containerList"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>

          <!-- 第三个选择器 -->
          <el-select v-model="selectedLines" placeholder="请选择" class="selector">
            <el-option
                v-for="option in linesOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <!-- 日志容器 -->
    <div class="log-container" v-if="activeIndex ==='2'">

      <codemirror
          v-model="rawLogData"
          placeholder=""
          :style="{ height: editorHeight }"
          v-bind="logOptions"
          :extensions="extensions"
          disabled="true"
                />
    </div>
    <!-- 日志容器 -->
    <div class="log-container" v-if="activeIndex ==='3'">

      <codemirror
          v-model="yamlContent"
          placeholder=""
          :style="{ height: editorHeight }"
          v-bind="logOptions"
          :extensions="extensions"
      />
    </div>
    <!-- 第二部分: 表格 -->
    <div class="table-wrapper shadow" v-if="activeIndex ==='1'">
      <el-table :data="tableData" style="width: 100%" row-key="podName"  >
          <el-table-column type="expand">
            <template #default="{ row }">
              <div class="parent-container">
                <div class="expanded-content">
                  <el-table :data="row.expanded?.slice(1)" style="width: 100%" class="row">
                    <el-table-column
                        class-name="text-center"
                        v-for="(label, prop) in row.expanded[0]"
                        :key="prop"
                        :label="label"
                        :prop="prop"
                        align="center"
                        header-align="center">
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </template>
          </el-table-column>

        <el-table-column prop="podName" label="Pod名" width="180px" align="center">
          <template #default="{ row }">
            <div>
              <p style="color: #4795EE; margin: 0;">{{ row.podName }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="状态" width="200px" align="center">
          <template #default="{ row }">
            <div>
              <el-tooltip class="item" effect="dark" placement="top" :content="row.FailedMessage">
                <el-tag class="ml-2" :type="getTagType(row.Status)">{{ row.Status }}</el-tag>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="HostIp" label="实例所在节点IP" align="center" width="200px">
          <template #default="{ row }">
            <div style="display: flex; align-items: center;justify-content: center;height: 100%">
              {{ row.HostIp }}
              <img v-if="row.showLoading" src="@/assets/load.svg" class="loading-icon" alt="loading"/>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="podIp" label="实例IP" align="center" width="200px">
          <template #default="{ row }">
            <div style="display: flex; align-items: center;justify-content: center;height: 100%">
              {{ row.podIp }}
              <img v-if="row.showLoading" src="@/assets/load.svg" class="loading-icon" alt="loading"/>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="RunningTime" label="运行时间" align="center" width="155px">
          <template #default="{ row }">
            <div>
              <el-tag class="ml-2" type="warning">{{row.RunningTime}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="155px">
          <template #default="{ row }">
            <div>
              <el-tag class="ml-2" type="warning">{{row.createTime}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="restartCount" label="重启次数" align="center" width="155px">
          <template #default="{ row }">
            <div>
              <el-tag class="ml-2" type="warning">{{row.restartCount}}</el-tag>
            </div>
          </template>
        </el-table-column>


        <el-table-column prop="Operation" label="操作" align="center">
          <template #default="{ row }">
            <div class="button-group">

              <el-button size="small" color="#5AABFF"  plain @click="viewYAML(row)">
                <el-icon><EditPen /></el-icon>
                <span style="vertical-align: middle"> YAML </span>
              </el-button>
              <el-button size="small"  color="#F58D79"  plain @click="confirmDelete(row)">
                <el-icon><Tickets /></el-icon>
                <span style="vertical-align: middle"> 删除 </span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total=podCount
          class="paginations"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog title="YAML信息" v-model="dialogVisible" width="45%" top="5%">

      <codemirror
          v-model="yamlContent"
          placeholder="请输入代码..."
          :style="{ height: '100%' }"
          v-bind="logOptions"
          :extensions="extensions"
      />
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button  type="primary" @click="updateDeploy()">更 新</el-button>
                </span>
      </template>
    </el-dialog>

  </div>


</template>

<script setup>
import {
  DAEMONSET_DETAIL,
  DAEMONSET_POD_LIST,
  DELETE_DEPLOYMENT, DELETE_POD, DEPLOYMENT_DETAIL,
  DEPLOYMENT_LIST,
  DEPLOYMENT_POD_LIST,
  GET_NS_POD_COUNT,
  NAMESPACE_LIST, POD_CONTAINERS, POD_DETAIL,
  POD_LIST, POD_LOGS, STATEFULSET_POD_LIST
} from "../../../api/k8s.js";
import {computed, nextTick, onBeforeMount, reactive, ref, watch} from "vue";
import { Codemirror } from 'vue-codemirror'

import router from "@/router/index.js";
import {ElMessage, ElMessageBox} from "element-plus";
import json2yaml from "json2yaml";
import {javascript} from "@codemirror/lang-javascript";
import {oneDark} from "@codemirror/theme-one-dark";
import _ from "lodash";
const extensions = [javascript(),oneDark]
const activeIndex = ref('1')
import { useRoute } from 'vue-router';


const handleSelect = (key, keyPath) => {
  console.log(key, keyPath)
  activeIndex.value = key; // 更新当前选中的菜单项
  if (key === '1') {
    getPodsData(); // 当选中Pod管理时，调用getPodsData函数
  }else if (key === '3'){
    getPodYamlData()
  }
}
const selectedPodName = ref(null); // 用于双向绑定选中的Pod名称

// 假设这是从某处获取的日志字符串
const rawLogData = ref('暂无日志');

// 将原始日志字符串分割成行数组
const logLines = computed(() => rawLogData.value.split('\n'));
const currentPage = ref(1)
const namespaces = ref([]); // 用于存储命名空间列表
const selectedNamespace = ref('default'); // 用于存储用户选择的命名空间
let pageSize = ref(5)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
// 在 <script setup> 中
const { type,deploymentName, namespace } = defineProps({
  type: String,
  deploymentName: String,
  namespace: String
});
const route = useRoute();
// 假设有三组选择器选项
const selectorOptions1 = ref([
  { label: '选项 1.1', value: '1.1' },
  { label: '选项 1.2', value: '1.2' },
  // ...其他选项
]);

const selectorOptions2 = ref([
  { label: '选项 2.1', value: '2.1' },
  { label: '选项 2.2', value: '2.2' },
  // ...其他选项
]);

const selectorOptions3 = ref([
  { label: '选项 3.1', value: '3.1' },
  { label: '选项 3.2', value: '3.2' },
  // ...其他选项
]);
// 第一个选择器变化时触发的函数
function handlePodChange(newValue) {
  // 当第一个选择器的值变化时，调用getPodDetailData函数
  console.log("================================")
  console.log(podN.value)
  if (podN.value !== ""){
      getContainerLogs()
  }
  getPodDetailData(newValue);
}
const handleInput = _.debounce(async () => {
  await search();
}, 500); // 使用 lodash 的 debounce 函数来防抖，防止搜索操作太频繁
function handleContainers(newValue) {
  // 当第一个选择器的值变化时，调用getPodDetailData函数
  console.log("================================")
  getContainerLogs(newValue);

}
// 为每个选择器定义模型来持有选中的值
const selectedValue1 = ref(null);
const selectedValue2 = ref(null);
const selectedLines = ref(50);
const linesOptions = [
  { label: '50行', value: 50 },
  { label: '100行', value: 100 },
  { label: '300行', value: 300 },
  { label: '500行', value: 500 },
  { label: '1000行', value: 1000 },
];

const logOptions = ref({
  tabSize: 4,
  mode: { name: 'yaml', json: true },
  theme: 'base16-light',
  styleActiveLine: true,
  lineNumbers: true,
  line: true,
  readOnly: true,
  indentWithTabs: true,
  smartIndent: true,
  indentUnit: 10,
  foldgutter: true,
  gutters: [
    'CodeMirror-linenumbers',
    'CodeMirror-foldgutter',
    'CodeMirror-lint-markers'
  ],
  lineWrapping: true, // 代码折叠
  foldGutter: true,
  matchBrackets: true, // 括号匹配
  autoCloseBrackets: true,
  showCursorWhenSelecting: true,
  cursorHeight: 0.85,

})
// 计算编辑器高度
const editorHeight = computed(() => {
  const lineHeight = 20; // 假设每行的高度
  return `${selectedLines.value * lineHeight}px`;
});
// 假设这是你的数据源
const state = reactive({
  tableData: [
    // 这里放入你的表格数据
  ],
  // 更多数据或状态...
});


const search = async () => {
  console.log('执行搜索:', searchText.value);
  console.log(type)
  try {
    if (type == 'daemonset'){
      const searchParameters = reactive({
        page_size: pageSize,
        page_number: currentPage,
        filterName: searchText.value,
        daemonsetName: deploymentName,
        namespace: namespace
      })
      console.log(searchParameters)
      const resp = await DAEMONSET_POD_LIST(searchParameters);
      console.log("牛逼：：：",resp)
      // // 初始化expandedData数组并添加表头

      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: { status: '-' }
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ?calculateRunningTime(item.status.startTime): '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================",newTableData)
      tableData.value = newTableData
      // 更新部署计数
      podCount.value = resp.data.total;
    }else if (type === "statefulset"){
      const searchParameters = reactive({
        page_size: pageSize,
        page_number: currentPage,
        filterName: searchText.value,
        statefulsetName: deploymentName,
        namespace: namespace
      })
      const resp = await STATEFULSET_POD_LIST(searchParameters);
      console.log("牛逼：：：", resp)
      // // 初始化expandedData数组并添加表头
      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: {status: '-'}
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ? calculateRunningTime(item.status.startTime) : '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================", newTableData)
      tableData.value = newTableData
      podCount.value = resp.data.total;
    }
    else if (type == 'deployment'){
      const searchParameters = reactive({
        page_size: pageSize,
        page_number: currentPage,
        filterName: searchText.value,
        deploymentName: deploymentName,
        namespace: namespace
      })
      const resp = await DEPLOYMENT_POD_LIST(searchParameters);
      console.log("牛逼：：：", resp)
      // // 初始化expandedData数组并添加表头
      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: {status: '-'}
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ? calculateRunningTime(item.status.startTime) : '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================", newTableData)
      tableData.value = newTableData
      podCount.value = resp.data.total;
    }

  } catch (e) {
  console.log(e);
}

}
const confirmDelete =  (row) => {confirmDelete

  ElMessageBox.confirm(
      `确定要删除Pod"${row.podName}" 吗?`,
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const deletePodParameters = reactive({
      podName: row.podName,
      namespace: namespace,
    })
    try {
      const resp = await DELETE_POD(deletePodParameters)
      console.log("————————————————",resp)
      ElMessage({
        type: 'success',
        message: `Pod "${row.podName}" 已被删除`
      });
      getPodsData()

    }catch (e){
      console.log(e)
      ElMessage.error(`删除失败: ${e}`);
    }
  }).catch(() => {

  });
};
const getTagType = (status) => {
  return status === 'Running' ? 'success' : 'danger';
};
const dialogVisible = ref(false);
let yamlContent = ref('');

var podCount = ref(0)

const namespaceAllParameters = reactive({
  page_size: 100000,
  page_number: currentPage.value,
  namespaces: selectedNamespace.value
})
const refresh = () => {
  getPodsData()
  console.log('刷新表格数据');
};
const updateParameters = reactive({
  podName: "",
  namespace: namespace,
  content: ""
})


const goBack = ()=>{
  router.go(-1)
}
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  namespaceAllParameters.page_size = val
  localStorage.setItem('nspageSize',val)
  getPodsData()
}
const viewYAML = (row) => {
  console.log('显示YAML信息', row.podName);
  // 这里可以编写显示YAML信息的逻辑
  // 假设提供了 `getYAMLContent` 方法来获取 YAML 内容
  // 直接使用传入的 row 作为 YAML 内容
};
const getPodYamlData = async ()=>{
  console.log(deploymentName,"---------------????-----------------")
  try {
    const PodDetailparams = reactive({
      daemonSetName: deploymentName,
      namespace: namespace
    })
    const resp = await DAEMONSET_DETAIL(PodDetailparams)
    console.log("yaml =======",json2yaml.stringify(resp.data))
    yamlContent.value = json2yaml.stringify(resp.data); // 确保将数据赋值给 yamlContent
    updateParameters.content = yamlContent.value

  }catch (e){
    console.log(e)
    console.log("你吗")
  }
}
let containerList = ref([])
let podN  = ref('')
const getPodDetailData = async (podName)=>{
  try {
    const PodDetailparams = reactive({
      podName: podName,
      namespace: namespace
    })
    podN = podName
    console.log("ddddddddd",PodDetailparams)
    const resp = await POD_CONTAINERS(PodDetailparams)
    console.log("cccccccc",resp)
    containerList = resp.data.map((item) => item.name);
    // console.log("yaml =======",json2yaml.stringify(resp.data))
    // yamlContent.value = json2yaml.stringify(resp.data); // 确保将数据赋值给 yamlContent
    // currentDeployName.value = resp.data.metadata.name
    // updateParameters.content = yamlContent.value
    // await  nextTick()
    // dialogVisible.value = true;

  }catch (e){
    console.log(e)
    console.log("你吗")
  }
}

const getContainerLogs = async (containerName)=>{
  try {
    const PodDetailparams = reactive({
      podName: podN,
      namespace: namespace,
      containerName: containerName
    })
    console.log("ddddddddd",PodDetailparams)
    const resp = await POD_LOGS(PodDetailparams)
    rawLogData.value = resp.data
    // console.log("yaml =======",json2yaml.stringify(resp.data))
    // yamlContent.value = json2yaml.stringify(resp.data); // 确保将数据赋值给 yamlContent
    // currentDeployName.value = resp.data.metadata.name
    // updateParameters.content = yamlContent.value
    // await  nextTick()
    // dialogVisible.value = true;

  }catch (e){
    console.log(e)
    console.log("你吗")
  }
}

const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  namespaceAllParameters.page_number = val
  localStorage.setItem('nscurrentPage', val); // 将当前页保存在 localStorage

  getPodsData()
}


const searchText = ref('');
const tableData = ref([
  {
    podName: "",
    Status: '',
    HostIp: '-',
    podIp: '-',
    RunningTime: '',
    creationTimestamp:'',
    restartCount: '',
    createTime:"",
    Operation:"",
    expanded:{},
    FailedMessage: '',
  },
  // ...其他数据项
]);
const podParameters = reactive({
  page_size: pageSize,
  page_number: currentPage,
  deploymentName: deploymentName,
  namespace: namespace,
})
const calculateRunningTime = (startTime) => {
  const now = new Date();
  const startedAt = new Date(startTime);
  const diff = now - startedAt;
  const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
  const diffHours = Math.floor((diff / (1000 * 60 * 60)) % 24);
  return `${diffDays}天${diffHours}时`;
};
const getPodsData = async () => {
  console.log(type,"typeaaaaa================================================================")
  console.log(podParameters,'--------------------------------')

  try {
    if (type == 'daemonset'){
      const podParameterss = reactive({
        page_size: pageSize,
        page_number: currentPage,
        daemonsetName: deploymentName,
        namespace: namespace,
      })
      const resp = await DAEMONSET_POD_LIST(podParameterss);
      console.log("牛逼：：：",resp)
      // // 初始化expandedData数组并添加表头

      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: { status: '-' }
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ?calculateRunningTime(item.status.startTime): '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================",newTableData)
      tableData.value = newTableData
      // 更新部署计数
      podCount.value = resp.data.total;
        return
    }else if (type == 'statefulset'){
      const podParameters = reactive({
        page_size: pageSize,
        page_number: currentPage,
        statefulsetName: deploymentName,
        namespace: namespace,
      })
      const resp = await STATEFULSET_POD_LIST(podParameters);
      console.log("牛逼：：：",resp)
      // // 初始化expandedData数组并添加表头

      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: { status: '-' }
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ?calculateRunningTime(item.status.startTime): '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================",newTableData)
      tableData.value = newTableData
      // 更新部署计数
      podCount.value = resp.data.total;
      return
    } else if (type == 'deployment'){
      const resp = await DEPLOYMENT_POD_LIST(podParameters);
      console.log("牛逼：：：",resp)
      // // 初始化expandedData数组并添加表头

      // 遍历每个 Pod 并构造其展开信息
      const newTableData = resp.data.items?.map(item => {
        const conditionsMessage = item.status.conditions?.map(condition => condition.message).join(", ") || "";

        // 表头数据，将直接作为第一个元素添加到每个expanded中
        const headerData = {
          containerName: '容器名称',
          image: '镜像版本号',
          podIp: 'PodIP',
          restartCount: '重启次数',
          status: '状态'
        };

        // 构造容器状态信息
        // 处理containerStatuses，以显示restartCount和state
        const podExpData = (item.status.containerStatuses || item.spec.containers.map(container => ({
          name: container.name,
          image: container.image,
          // 如果没有containerStatuses，设置restartCount和state为"-"
          restartCount: '-',
          state: { status: '-' }
        }))).map(container => {
          let status = '-';
          let conditionMessage = '';

          // 解析容器状态
          if (container.state) {
            if (container.state.running) {
              status = '运行中';
            } else if (container.state.waiting) {
              status = '等待中';
              conditionMessage = container.state.waiting.message || conditionsMessage;
            } else if (container.state.terminated) {
              status = '已终止';
              conditionMessage = container.state.terminated.message || conditionsMessage;
            }
          } else {
            // 如果容器还没有状态（可能是pod还在Pending阶段），使用Pod的conditions信息
            conditionMessage = conditionsMessage;
          }

          return {
            containerName: container.name || '-',
            image: container.image || '-',
            podIp: item.status.podIP || '-',
            restartCount: container.restartCount !== undefined ? container.restartCount.toString() : '-',
            status: status,
            conditionMessage: conditionMessage  // 存储条件消息，以便于前端显示提示
          };
        });
        podExpData.unshift(headerData);

        const failureMessage = getFailureMessage(item);

        // 构造表格数据项，并包含展开属性
        return {
          // ...其他属性...
          FailedMessage: failureMessage,
          podName: item.metadata.name,
          Status: item.status.phase,
          HostIp: item.status.hostIP,
          podIp: item.status.podIP,
          RunningTime: item.status.startTime ?calculateRunningTime(item.status.startTime): '0天0时',
          restartCount: calculateTotalRestartCount(item),
          createTime: formatDateTime(item.metadata.creationTimestamp),
          expanded: podExpData, // 添加expanded字段
        };
      });
      console.log("================================",newTableData)
      tableData.value = newTableData
      // 更新部署计数
      podCount.value = resp.data.total;
    }

  } catch (e) {
    console.log(e);
  }
};

function getStatus(state) {
  if (!state) return '未知';

  if (state.running) {
    return '运行中';
  } else if (state.waiting) {
    return `等待中 (${state.waiting.reason})`;
  } else if (state.terminated) {
    return `已终止 (${state.terminated.reason})`;
  } else {
    return '未知';
  }
}

const getFailureMessage = (pod) => {
  // 假设失败信息在条件列表中
  if (pod.status && pod.status.conditions) {
    const unschedulableCondition = pod.status.conditions.find(condition => condition.reason === 'Unschedulable');
    return unschedulableCondition ? unschedulableCondition.message : 'No failure message';
  }
  return 'No failure message';
};
const calculateTotalRestartCount = (pod) => {
  if (pod.status && Array.isArray(pod.status.containerStatuses)) {
    return pod.status.containerStatuses.reduce((total, containerStatus) => {
      return total + (containerStatus.restartCount || 0);
    }, 0);
  }
  return '-';
};


// 设置watcher来监听selectedNamespace的改变
watch(selectedNamespace, (newNamespace) => {
  // 更新deploymentParameters中的namespace
  podParameters.namespace = newNamespace;

  // 重新调用getDeployData以获取新命名空间的部署数据
  getPodsData();
});
const formatDateTime = (dateTimeString) => {
  return dateTimeString.replace('T', ' ').replace('Z', '');
};
onBeforeMount( async ()=> {
  // 尝试从 localStorage 中读取状态
  const savedPageSize = localStorage.getItem('nspageSize');
  const savedCurrentPage = localStorage.getItem('nscurrentPage');

  // 如果存在则更新到响应式变量中
  // if (savedPageSize) {
  //   pageSize.value = parseInt(savedPageSize, 10);
  // }
  // if (savedCurrentPage) {
  //   currentPage.value = parseInt(savedCurrentPage, 10);
  // }
  getPodsData()
  // getNSAllData()

});
</script>

<style scoped>
.loading-icon {
  width: 20px; /* 或者您希望的任何尺寸 */
  height: 20px; /* 保持与宽度相同以保持图标的纵横比 */
  margin-left: 5px; /* 添加一点空间在状态文本和图标之间 */
  animation: loading-spin 2s linear infinite;
}

/* 如果需要，可以移除这个类，因为它可能会导致对齐问题 */
/* .loader {
  animation: loader-spin 1s linear infinite;
} */

@keyframes loading-spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.container {
  margin: 10px;
}
.deployment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  margin: 10px;
  margin-bottom: -10px;
  background: #FFF;
  border: 2px solid #ebeef5;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 新增左侧部分样式，放置“命名空间：”文本和下拉框 */
.left-section {
  display: flex;
  align-items: center;
}

/* 确保下拉框和文本在同一行 */
.el-select {
  margin-left: 10px; /* 为下拉框添加左侧间隔 */
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 添加此属性对子元素进行分散对齐 */
  margin-bottom: 0px;
  gap: 10px;
  padding: 10px;
  background: #FFF;
  border: 2px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-input {
  /*flex-grow: 1;*/
  width: 200px;
}

.table-wrapper {
  background: #FFF;
  border: 2px solid #ebeef5; /* 浅色边框线 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.paginations {
  margin-top: 10px;
  margin-left: 20px;
  margin-bottom: 10px;
}
/* 左侧组合样式，创建按钮和搜索框靠在一起 */
.left-group {
  display: flex;
  align-items: center;
  gap: 10px; /* You can adjust the gap as needed */
}

/* 右侧刷新按钮 */
.right-group {
  display: flex;
  align-items: center;
}
.yaml-content {
  background-color: #f5f5f5;
  border-left: 3px solid #4795EE;
  padding: 15px;
  white-space: pre-wrap;
  text-align: left;
  margin: 20px 0;
  overflow-x: auto;
}
.status-active {
  color: #67C23A;
}

.status-inactive {
  color: red;
}
.dialog-footer {
  /*text-align: right;*/
  display: flex;
  justify-content: flex-end;
  padding: 8px;
}




.deployment-header {
  display: flex;
  align-items: center;
  height: 30px;
  padding: 10px;
  margin: 10px;
  margin-bottom: -10px;
  background: #FFF;
  border: 2px solid #ebeef5;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}



.form-item-with-help {
  margin-top: 10px;
  margin-left: 20px;
}
.form-item-with-resource {
  margin-top: 10px;
  margin-left: 20px;
}
.form-item {
  flex-wrap: wrap; /* 确保换行 */
  /*align-items: center; !* 如果需要垂直居中 *!*/
  margin-bottom: 10px; /* 保持垂直间距 */
}

.input-item {
  width: 200px;
  margin-right: 10px;
}
.help-text {
  display: block; /* 保证帮助文本在新的行显示 */
  font-size: 12px;
  width: 1000px;
  color: #999999;
  margin-top: 5px;
}
.input-with-help {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
}
.input-deployname {
  width: 300px; /* 限制这个div的宽度 */
  display: flex;
  flex-direction: column; /* 让子元素垂直排列 */
}
.input-containername {
  width: 250px; /* 限制这个div的宽度 */
  display: flex;
  margin-left: -50px;
  flex-direction: column; /* 让子元素垂直排列 */
}

.add-button {
  margin-top: -20px; /* 添加按钮与输入行之间的空间 */
  margin-left: 200px;
}

.input-container-cpu {
  display: flex;
  flex-direction: column;
  /*padding-left: -20px; !* 往右移动整个容器 *!*/

}

.cpu-label {
  margin-bottom: 5px; /* 调整为所需的间距 */
  margin-left: -50px;
}


.container {
  margin: 10px;
}
.item-container {
  margin-bottom: 10px;
}
.content-container {
  background-color: #F2F2F2;
  padding: 10px;
  display: flex;
  width: 700px;
  justify-content: space-between;
  align-items: center;
  transition: height 0.3s;
  overflow: hidden;
  position: relative;

}
.content-container.collapsed {
  height: 40px;
}
.info {
  display: flex;
  align-items: center;
}
.actions {
  position: absolute;
  right: 10px; /* 调整为需要的值 */
  top: 10px; /* 调整为需要的值 */
}



.input-row {
  display: flex;
  align-items: center;
  gap: 10px;
  /*margin-left: -50px;*/
}
.input-row .el-input {
  flex: 1;
}

.input-row label {
  margin-left: 10px; /* 或者需要的任何值 */
}

.input-row .el-input .el-input__inner {
  width: 100%; /* 让输入框充满其容器 */
}


.input-containername p {
  margin-bottom: 10px; /* 为“CPU：”下方添加一些间隔 */
}

.form-item-resource {
  margin-left: 20px; /* 整个表单项向右移动 20px */
  margin-top: 10px;
}
.custom-form-item {
  height: auto;
  overflow: auto;
}
.check-method-container,
.execution-command-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px; /* 添加一些垂直间距 */
}

.method-label {
  width: 100px;
  margin: 10px;
  margin-right: 20px; /* 文本与选择框/输入框之间的间隔 */
}
.command-label {
  /*margin-right: 20px; !* 文本与输入框之间的间隔 *!*/
  width: 100px;
  margin: 10px;

}
.livenessdiv {
  background-color: white;
  width: 500px;
}
.port-range {
  margin-left: 10px;
}
.input-healthContainer {
  margin-left: -50px;
}
.el-select,
.el-input {
  /*flex-grow: 1; !* 输入框和选择框将占据剩余空间 *!*/
  max-width: calc(100% - 100px); /* 限制最大宽度，这里的100px是示例，可以根据实际情况调整 */
}
.button-group {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px; /* 调整按钮之间的间隔 */
}
.paginations {
  margin-top: 10px;
  margin-left: 20px;
  margin-bottom: 10px;
}
.parent-container {
  display: flex;  /* 设置父容器为flex布局 */
  justify-content: center;  /* 水平居中 */
  align-items: center;  /* 垂直居中 */
  height: 100%;  /* 父容器需要有确定的高度 */
  background-color: #F3F4F7;
}

.expanded-content {
  width: 95%;
  border: 1px solid #dcdcdc; /* 表格四周的外边框 */
  background-color: white;
  margin-top: 10px;
  margin-bottom: 10px;
}

.row {
  display: flex;
}

.cell {
  flex: 1; /* 让所有单元格平均分配空间 */
  text-align: center;
  padding: 10px; /* 单元格内边距 */
  border-top: none; /* 默认去除顶部边框 */

}

/* 只给第一行的最底部添加边框 */
.row:first-child .cell {
  border-bottom: 1px solid #dcdcdc;
}
/* CSS 类来居中表格单元格内容 */
.text-center {
  text-align: center;
}

::v-deep .text-center {
  text-align: center !important;
}
/* 设置选择器的布局 */
.selectors {
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中对齐 */
  margin-left: 20px; /* 距离返回按钮的左边距 */
}

/* 设置选择器的样式 */
.selector {
  margin-right: 20px; /* 选择器之间的右边距 */
}

/* 移除最后一个选择器的右边距 */
.selector:last-child {
  margin-right: 0;
}
/* 日志行样式 */
.log-line {
  display: flex;
}

/* 行号样式 */
.line-number {
  color: #999;
  min-width: 50px; /* 为行号保留足够宽度 */
  text-align: right; /* 行号右对齐 */
  padding-right: 15px; /* 行号和内容之间的间距 */
}

/* 日志内容样式 */
.line-content {
  flex: 1;
  white-space: pre; /* 保留空格和格式 */
}
.log-container {
  height: 700px;
}
</style>
